<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { useSystemStore } from '@/stores'
import { useRouter, useRoute } from 'vue-router'
import { RouterView } from 'vue-router'
import { useUserStore } from './stores/user'

// 获取router和systemStore
const router = useRouter()
const systemStore = useSystemStore()
const route = useRoute()
const userStore = useUserStore()

// 全局检测是否在CEF浏览器中运行
const isCEF = ref(false)

// Token检查函数
const checkTokenValidity = () => {
  // 如果没有Token或未登录，不需要检查
  if (!systemStore.isLogin) return
  
  // 获取Token过期时间（如果有）
  // 这部分逻辑取决于您的Token结构，可能需要调整
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      // 如果localStorage中没有token但状态是已登录，执行登出
      systemStore.logout()
      return
    }
    
    // 如果您的Token是JWT格式，可以解析并检查过期时间
    // 这里只是一个示例，您需要根据实际Token格式调整
    /*
    const tokenParts = token.split('.')
    if (tokenParts.length === 3) {
      const payload = JSON.parse(atob(tokenParts[1]))
      if (payload.exp && payload.exp * 1000 < Date.now()) {
        // Token已过期
        ElMessage.warning('登录已过期，请重新登录')
        systemStore.logout()
        
        // 如果当前不在登录页，跳转到登录页
        if (router.currentRoute.value.name !== 'login') {
          router.replace('/login')
        }
      }
    }
    */
  } catch (error) {
    console.error('Token验证错误:', error)
  }
}

// 保存定时器引用
let tokenCheckInterval

onMounted(() => {
  console.log('App mounted, current URL:', window.location.href)
  
  // 监听URL变化
  const handleUrlChange = () => {
    console.log('URL changed:', window.location.href)
  }
  
  window.addEventListener('hashchange', handleUrlChange)
  
  // 启动定时检查Token (每30秒检查一次)
  tokenCheckInterval = setInterval(checkTokenValidity, 30000)
  
  // 立即执行一次检查
  checkTokenValidity()
  
  // 检测是否为CEF环境
  const userAgent = navigator.userAgent.toLowerCase();
  isCEF.value = userAgent.includes('electron') || 
                userAgent.includes('cef') || 
                userAgent.includes('chrome-embedded') ||
                (window.chrome && !window.chrome.webstore);
  
  if (isCEF.value) {
    console.log('检测到CEF浏览器环境，应用全局CEF样式修复');
    document.body.classList.add('cef-browser');
    
    // 注入全局CEF下拉菜单修复样式
    const styleElement = document.createElement('style');
    styleElement.id = 'cef-global-fixes';
    styleElement.innerHTML = `
      /* 全局CEF浏览器样式修复 */
      .el-select-dropdown.el-popper {
        max-height: 300px !important;
        overflow: auto !important;
        background-color: #ffffff !important;
        border: 1px solid #e4e7ed !important;
        border-radius: 4px !important;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
      }
      
      .el-select-dropdown.el-popper .el-scrollbar,
      .el-select-dropdown.el-popper .el-scrollbar__wrap {
        max-height: 300px !important;
        overflow-y: auto !important;
        background-color: #ffffff !important;
      }
      
      .el-select-dropdown.el-popper .el-select-dropdown__wrap {
        max-height: 260px !important;
        background-color: #ffffff !important;
      }
      
      .el-select-dropdown.el-popper .el-select-dropdown__list {
        max-height: 260px !important;
        padding: 4px 0 !important;
        background-color: #ffffff !important;
      }
      
      .el-select-dropdown.el-popper .el-select-dropdown__item {
        height: 34px !important;
        line-height: 34px !important;
        max-height: 34px !important;
        padding: 0 8px !important;
        color: #606266 !important;
      }
      
      .el-select-dropdown.el-popper .el-select-dropdown__item.hover,
      .el-select-dropdown.el-popper .el-select-dropdown__item:hover {
        background-color: #f5f7fa !important;
      }
      
      /* 移除黑色竖线 */
      .el-popper::before,
      .el-popper::after,
      .el-select-dropdown::before,
      .el-select-dropdown::after,
      .el-popper .el-popper__arrow,
      .el-popper .el-popper__arrow::before {
        display: none !important;
        border: none !important;
        background: none !important;
      }
      
      /* 修复下拉菜单的遮罩层 */
      .el-overlay {
        background-color: transparent !important;
      }
      
      /* 修复body下的所有弹出元素 */
      body > .el-popper {
        background-color: #ffffff !important;
        border: 1px solid #e4e7ed !important;
        border-radius: 4px !important;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
      }
      
      /* 移除所有导致黑色线条的伪元素 */
      body > .el-popper::before,
      body > .el-popper::after {
        display: none !important;
      }
    `;
    document.head.appendChild(styleElement);
    
    // 处理所有下拉菜单相关元素的黑色竖线问题
    const removeBlackLines = () => {
      // 查找所有的popper元素
      const poppers = document.querySelectorAll('.el-popper, .el-select-dropdown');
      poppers.forEach(popper => {
        // 移除伪元素样式
        popper.style.setProperty('--el-popover-border-color', 'transparent', 'important');
        
        // 移除箭头元素
        const arrows = popper.querySelectorAll('.el-popper__arrow');
        arrows.forEach(arrow => {
          arrow.style.display = 'none';
          arrow.style.visibility = 'hidden';
          arrow.style.opacity = '0';
        });
        
        // 暂时禁用元素隐藏逻辑，以确保footer插槽正常显示
        // 如果需要移除黑色线条，可以使用更精确的选择器
        // const pseudoElements = Array.from(popper.children).filter(el => 
        //   el.classList.contains('specific-black-line-class')
        // );
        // pseudoElements.forEach(el => {
        //   el.style.display = 'none';
        // });
      });
    };
    
    // 全局监听所有下拉菜单的打开事件
    const fixDropdowns = () => {
      const dropdowns = document.querySelectorAll('.el-select-dropdown.el-popper');
      if (dropdowns.length > 0) {
        dropdowns.forEach(dropdown => {
          // 直接设置内联样式
          dropdown.style.cssText += 'max-height: 300px !important; overflow: auto !important; background-color: #ffffff !important; border: 1px solid #e4e7ed !important; border-radius: 4px !important; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;';
          
          const scrollbar = dropdown.querySelector('.el-scrollbar__wrap');
          if (scrollbar) {
            scrollbar.style.maxHeight = '260px';
            scrollbar.style.overflowY = 'auto';
            scrollbar.style.backgroundColor = '#ffffff';
          }
          
          // 修复选项项目样式
          const items = dropdown.querySelectorAll('.el-select-dropdown__item');
          items.forEach(item => {
            item.style.backgroundColor = '#ffffff';
            item.style.color = '#606266';
          });
        });
        
        // 移除黑色线条
        removeBlackLines();
      }
    };
    
    // 使用事件委托，监听整个document的点击事件
    document.addEventListener('click', (e) => {
      if (e.target && (e.target.classList.contains('el-select') || e.target.closest('.el-select'))) {
        // 当点击select时，延迟处理下拉菜单
        setTimeout(fixDropdowns, 50);
      }
      
      // 总是检查并移除黑色线条
      setTimeout(removeBlackLines, 100);
    });
    
    // 监视DOM变化，处理动态添加的下拉菜单
    const observer = new MutationObserver(mutations => {
      let shouldFixDropdowns = false;
      
      mutations.forEach(mutation => {
        if (mutation.type === 'childList' && mutation.addedNodes.length) {
          for (const node of mutation.addedNodes) {
            if (node.nodeType === 1 && 
                node.classList && 
                node.classList.contains('el-select-dropdown')) {
              shouldFixDropdowns = true;
              break;
            }
          }
        }
      });
      
      if (shouldFixDropdowns) {
        fixDropdowns();
        removeBlackLines();
      }
    });
    
    // 开始观察
    observer.observe(document.body, { childList: true, subtree: true });
    
    // 立即执行一次修复
    setTimeout(() => {
      fixDropdowns();
      removeBlackLines();
    }, 500);
    
    // 添加定时器，持续检查并修复可能出现的问题
    const intervalId = setInterval(() => {
      fixDropdowns();
      removeBlackLines();
    }, 2000);
    
    // 组件卸载时清理
    onUnmounted(() => {
      if (intervalId) {
        clearInterval(intervalId);
      }
      observer.disconnect();
    });
  }
  
  onUnmounted(() => {
    window.removeEventListener('hashchange', handleUrlChange)
    
    // 清除定时器
    if (tokenCheckInterval) {
      clearInterval(tokenCheckInterval)
    }
  })
})
</script>

<template>
  <RouterView />
</template>

<style></style>
